<template> <el-upload
 :http-request="customUpload"
 list-type="text"
 :before-upload="beforeUpload"
 :on-success="handleUploadSuccess"
 :on-error="handleUploadError"
 >
 <el-button type="primary">点击上传</el-button>
</el-upload>
 <img :src="data.imageSrc" class="pic" />
</template>
<script setup>
import axios from "axios";
import { ElMessage } from "element-plus";
import { reactive } from "vue";

let data = reactive({
 imageSrc:
 "https://qiangzi321.oss-cn-beijing.aliyuncs.com/ayg/NSHM_PHOTO_2023_6_29_15_13_58.jpg",
 fileName: "",
});
let customUpload = async (option) => {
//上传触发
 const formData = new FormData();
 formData.append("file", option.file); //option.file要上传的文件

 try {
 const response = await axios.post(
 "http://localhost:8882/upload",
 formData,
 {
 headers: {
 "Content-Type": "multipart/form-data",
 },
 }
 );
 ElMessage.success("上传成功");
 option.onSuccess(response.data);
} catch (error) {
 ElMessage.error("上传失败");
 option.onError(error);
 }
};
let beforeUpload = (file) => {
 //上传之前触发
 data.fileName = file.name;
return true;
};
let handleUploadSuccess = (response) => {
 //上传成功触发
 if (response) {
 data.imageSrc = response;//存下来返回的图片链接
 console.log(data.imageSrc); }
};
let handleUploadError = (error) => { //上传失败触发 ElMessage.error("上传失败:" + error);
};
</script>
<style scoped>
.pic { width: 200px; height: 200px;
 border: 1px solid black;
 border-radius: 5px;
}
</style>